/**
 * Copyright 2011 FeedDreamwork SIG
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.feeddreamwork;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

import javax.servlet.http.*;

import com.google.appengine.api.taskqueue.*;
import com.google.appengine.api.taskqueue.Queue;

import static com.google.appengine.api.taskqueue.TaskOptions.Builder.*;

public class UpdateDispatchServlet extends HttpServlet {
	private static final long serialVersionUID = 7995096854592603974L;

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");

		if (Utils.isNullOrEmpty(req.getHeader("X-AppEngine-Cron"))) {
			resp.sendError(403);
			return;
		}
		
		long time = new Date().getTime();
		long timeStamp = time / 60000;
		if (time % 60000 > 30000)
			timeStamp++;
		MiniCache.put("TIME", timeStamp);
		FeedInfoRepository feedInfoRepo = null;
		
		try {
			boolean doWrite = false;
			Map <String, Integer> feeds = null;
			try {
				feeds = (Map <String, Integer>) MiniCache.get("FEEDINFOS");
			} catch (Exception e) {}
			
			if (feeds == null) {
				feedInfoRepo = new FeedInfoRepository();
				List <FeedInfo> feedInfos = feedInfoRepo.getFeedInfos();
				feeds = new HashMap <String, Integer> ();
				for (FeedInfo feedInfo : feedInfos)
					feeds.put(feedInfo.getFeedId(), feedInfo.getFrequency());
				doWrite = true;
			}
			
			for (Entry <String, Integer> feed : feeds.entrySet())
				if ((timeStamp % (long) feed.getValue()) == 0) {
					Queue queue = QueueFactory.getDefaultQueue();
					queue.add(withUrl("/settings/updatefeed").param("feedid", feed.getKey()));
				}
			
			if (doWrite)
				MiniCache.put("FEEDINFOS", feeds);
		} finally {
			if (feedInfoRepo != null)
				feedInfoRepo.close();
		}
	}
}
